<?php

namespace AppBundle\Form;

use AppBundle\Entity\User;
use AppBundle\Repository\UserRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class LoginType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** @var  $data User*/
        $data = $builder->getData();
        $builder
            ->add('username',TextType::class,[
                'constraints'=>[
                    new NotBlank()
                ],
            ])
            ->add('password',PasswordType::class,[
                'constraints'=>[
                    new NotBlank(),
                    new Callback(
                        function($object,ExecutionContextInterface $context) use($data){
                            /** @var  $repository UserRepository*/
                            $repository = $data->getOptions()['repository'];
                            if(!$repository->checkLogin($data)){
                                $context->addViolation('用户名或密码错误');
                            }
                        })
                ]
            ]);
        $useroptions = $data->getOptions();
        if(isset($useroptions['confirmVerifyCode'])) {
            $builder->add('verifyCode', TextType::class, [
                'label'=>'验证码',
                'mapped'=>false,
                'constraints' => [
                    new NotBlank(),
                    new EqualTo([
                        'value' => $useroptions['confirmVerifyCode'],
                        'message'=>'验证码错误'
                    ]),
                ]
            ]);
        }
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {

    }
}
